<?php
/**
 * 收货地址验证器
 */
namespace app\api\validate;

use think\Validate;
use think\Db;

class AddressValidate extends Validate
{
    protected $rule = [
        'consigner'     => ['require'],
        'mobile'     => ['require', 'regex' => '^1[34578]\d{9}$'],
        'province'   => 'require|between:1,34',
        'city'       => 'require',
        'district'       => 'require|checkArea',
        'address'   => ['require'],
    ];

    protected $message = [
        'consigner.require' => '请设置收件人',
        'mobile.require' => '请设置联系方式',
        'mobile.regex' => '联系方式格式错误',
        'province.require' => '请选择城市所在地',
        'province.between' => '城市所在地选择有误',
        'city.require' => '请选择城市所在地',
        'district.require' => '请选择城市所在地',
        'address.require' => '请设置详细收货地址',
    ];

    /**
     * 验证地区
     */
    public function checkArea($value, $rule ,$data)
    {
    	$is_has = Db::name('region')->alias('a')
    			->field('a.*,b.parent_id as grandpa_id')
				->join('region b', 'a.parent_id=b.id', 'left')
				->where(['a.id' => $data['district'], 'a.parent_id' => $data['city'], 'b.parent_id' => $data['province']])
				->find();
	
		if (empty($is_has)) {
			return '请选择正确的地址';
		}
		return true;
    }

}